package chatserver.gui;


import chatserver.roles.Role;
import java.awt.Component;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JCheckBox;
import javax.swing.JPanel;

class RightListItem<E> {

    private String name;
    private List<E> roles;
    private JCheckBox checkBox;
    private CheckComboBox comboBox;
    private JPanel panel;
    private boolean hasModifier;

    public RightListItem(String name, boolean isSelected, boolean hasModifier, List<E> roles, List<E> selectedRoles) {
        this.name = name;
        this.roles = roles;

        this.hasModifier = hasModifier;

        checkBox = new JCheckBox();
        checkBox.setSelected(isSelected);

        if (hasModifier) {
            Map<Object, Boolean> data = new HashMap<Object, Boolean>();
            for (E role : roles) {
                if (selectedRoles != null && selectedRoles.contains(role)) {
                    data.put(role, true);
                } else {
                    data.put(role, false);
                }
            }
            comboBox = new CheckComboBox(data);
        }
        panel = new JPanel();
        panel.setLayout(new GridLayout(0, 2));

        panel.add(checkBox);
        if (hasModifier) {
            panel.add(comboBox);
        }

        checkBox.setText(name);

        checkBox.setVisible(true);
        if (hasModifier) {
            comboBox.setVisible(true);
        }

        panel.setOpaque(false);
        checkBox.setOpaque(false);
        if (hasModifier) {
            comboBox.setOpaque(false);
        }


        panel.setVisible(true);
    }

    public boolean isSelected() {
        return checkBox.isSelected();
    }

    public void setSelected(boolean isSelected) {
        checkBox.setSelected(isSelected);
    }

    @Override
    public String toString() {
        return name;
    }

    public Component getComponent() {
        return panel;
    }

    public boolean hasModifier() {
        return hasModifier;
    }

    public String getName() {
        return name;
    }

    public List<Integer> getSelectedRoleIds() {
        List<Integer> ret = new ArrayList<Integer>();

        Object[] selectedItems = comboBox.getSelectedItems();
        if (selectedItems != null) {
            for (Object obj : selectedItems) {
                Role role = (Role) obj;
                ret.add(role.getSqlId());
            }
        }
        return ret;
    }
}